package com.unknowpupil.sell.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.unknowpupil.sell.common.BasePage;
import com.unknowpupil.sell.common.request.Result;
import com.unknowpupil.sell.converter.OrderForm2OrderDTO;
import com.unknowpupil.sell.dto.OrderDTO;
import com.unknowpupil.sell.exception.SellException;
import com.unknowpupil.sell.form.OrderForm;
import com.unknowpupil.sell.service.BuyerService;
import com.unknowpupil.sell.service.IOrderMasterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.xml.ws.Service;

/**
 * @Classname: BuyerOrderController
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2020/1/1 14:53
 * @Description:
 * @Version: 1.0
 */
@Api(tags = {"BuyerOrderController"}, description = "买家模块")
@RestController
@RequestMapping(value = "/api/buyer/order/")
@Slf4j
public class BuyerOrderController {
    @Autowired
    private IOrderMasterService orderMasterService;

    @Autowired
    private BuyerService buyerService;

    @ApiOperation(value = "创建订单", notes = "创建订单")
    @PostMapping("create")
    public Result create(@Valid OrderForm orderForm, BindingResult bindingResult){

        if(bindingResult.hasErrors()){
            log.error("[创建订单] 订单创建参数不健全，orderForm={}",orderForm);
            throw new SellException(1,"订单创建参数"+bindingResult.getFieldError().getDefaultMessage()+"不健全");
        }

        OrderDTO orderDTO = OrderForm2OrderDTO.convert(orderForm);
        OrderDTO result = orderMasterService.create(orderDTO);
        return Result.ok(result.getOrderId());
    }
    //订单列表
    @GetMapping("list")
    public Result<IPage<OrderDTO>> list(BasePage basePage,@RequestParam("openId") String openId){
        if(StringUtils.isBlank(openId)){
            return Result.error("openId 不能够为空");
        }
        IPage<OrderDTO> result = orderMasterService.findListWithPage(openId,basePage);
        return Result.ok(result);
    }

    //订单详情
    @GetMapping("detail")
    public Result<OrderDTO> detail(@RequestParam("openId") String openId,
                                   @RequestParam("orderId") String orderId){
        OrderDTO orderDTO = buyerService.findOrderOne(openId,orderId);
        return Result.ok(orderDTO);

    }
    //取消订单
    @GetMapping("cancel")
    public Result cancel(@RequestParam("openId") String openId,
                                   @RequestParam("orderId") String orderId){
        OrderDTO orderDTO = buyerService.cancelOrder(openId, orderId);
        return Result.ok(null);

    }
}
